﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using JBeamLibrary.VehicleParts;
using JBeamLibrary.VehicleParts.Elements;

namespace DriveBeamEditor.Controls.BeamNG.Controls
{
    public partial class NodeSelectionControl : UserControl
    {
        #region Fields

        private VehiclePart _vehiclePart;

        public event EventHandler VehiclePartChanged;
        public event EventHandler<Node> NodeValidated;
        public event EventHandler<Node> SelectedNodeChanged;

        #endregion

        #region Properties

        public VehiclePart VehiclePart
        {
            get { return _vehiclePart; }
            set
            {
                if (_vehiclePart == value) return;
                _vehiclePart = value;
                OnVehiclePartChanged();
            }
        }

        public Node SelectedNode
        {
            get { return nodesSource.Current as Node; }
            set { listNodes.SelectedItem = value; }
        }

        #endregion

        #region CTORs

        public NodeSelectionControl()
        {
            InitializeComponent();
        }

        #endregion

        #region Events

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (DesignMode) return;

            BindNodes();
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            if (Visible)
                BindNodes();
            base.OnVisibleChanged(e);
        }

        private void listNodes_DoubleClick(object sender, EventArgs e)
        {
            if (NodeValidated != null)
                NodeValidated(this, SelectedNode);
        }

        private void listNodes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SelectedNodeChanged != null)
                SelectedNodeChanged(this, SelectedNode);
        }

        #endregion

        #region Methods

        private void BindNodes()
        {
            nodesSource.DataSource = null;
            nodesSource.DataSource = VehiclePart != null ? VehiclePart.NodeSection.ElementCollection : null;
            nodesSource.ResetBindings(true);
        }

        private void OnVehiclePartChanged()
        {
            boxNodes.Text = VehiclePart != null
                ? string.Format("{0}", VehiclePart.Description)
                : @"Nodes";

            BindNodes();

            if (VehiclePartChanged != null)
                VehiclePartChanged(this, new EventArgs());
        }

        public void Reload()
        {
            BindNodes();
        }

        #endregion
    }
}
